import backtrader as bt

# backtrader实现动态止损
class DynamicStopLossStrategy(bt.Strategy):
    params = (
        ("initial_stop_loss_percentage", 2),
        ("trailing_stop_loss_percentage", 1),
    )

    def __init__(self):
        self.dataclose = self.datas[0].close
        self.order = None
        self.buy_price = None
        self.initial_stop_loss_price = None
        self.trailing_stop_loss_price = None

    def notify_order(self, order):
        if order.status in [order.Submitted, order.Accepted]:
            return

        if order.status in [order.Completed]:
            if order.isbuy():
                self.buy_price = order.executed.price
                self.initial_stop_loss_price = self.buy_price * (
                    1 - self.params.initial_stop_loss_percentage / 100
                )
                self.trailing_stop_loss_price = self.buy_price
                self.log(
                    f"BUY EXECUTED, Price: {order.executed.price}, Cost: {order.executed.value}, Size: {order.executed.size}"
                )
            elif order.issell():
                self.log(
                    f"SELL EXECUTED, Price: {order.executed.price}, Cost: {order.executed.value}, Size: {order.executed.size}"
                )
            self.order = None

        elif order.status in [order.Canceled, order.Margin, order.Rejected]:
            self.log("Order Canceled/Margin/Rejected")

    def next(self):
        if self.position:
            current_price = self.dataclose[0]
            # 更新动态止损价格
            if current_price > self.trailing_stop_loss_price:
                self.trailing_stop_loss_price = current_price * (
                    1 - self.params.trailing_stop_loss_percentage / 100
                )
            # 判断是否达到止损条件
            if (
                current_price < self.trailing_stop_loss_price
                or current_price < self.initial_stop_loss_price
            ):
                self.close()

    def log(self, txt):
        dt = self.datas[0].datetime.date(0)
        print(f"{dt}, {txt}")


if __name__ == "__main__":
    cerebro = bt.Cerebro()
    data = bt.feeds.GenericCSVData(
        dataname="your_data.csv",
        dtformat=("%Y-%m-%d"),
        datetime=0,
        open=1,
        high=2,
        low=3,
        close=4,
        volume=5,
        openinterest=-1,
    )
    cerebro.adddata(data)
    cerebro.addstrategy(DynamicStopLossStrategy)
    cerebro.broker.setcash(100000.0)
    cerebro.broker.setcommission(commission=0.001)
    print("Starting Portfolio Value: %.2f" % cerebro.broker.getvalue())
    cerebro.run()
    print("Final Portfolio Value: %.2f" % cerebro.broker.getvalue())
